package lxh.com.union.logic_business.util;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import lxh.com.union.base.base.BaseActivity;

/**
 * Created by Administrator on 2017/11/27.
 */

public class FragmentHelper {
    private Fragment showFragment;
    private BaseActivity mContext;
    private static FragmentHelper mFragmentHelper;

    private FragmentHelper(BaseActivity context) {
        mContext=context;
    }

    /**
     * 单例.
     * @param context
     * @return
     */
    public static FragmentHelper getInsctance(BaseActivity context){
        if (mFragmentHelper==null){
            synchronized (FragmentHelper.class){
                if (mFragmentHelper==null){
                    mFragmentHelper=new FragmentHelper(context);
                }
            }
        }
        return mFragmentHelper;
    }
    /**
     * 切换fragment.
     *
     * @param resid fragment容器id
     * @param fragment 需要切换的fragment
     * @param tag 标记
     */
    public void fragmentManager(int resid, Fragment fragment, String tag) {
        FragmentManager fragmentManager =mContext.getSupportFragmentManager();
        //开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //隐藏正在显示的Fragment对象
        if (showFragment != null) {
            fragmentTransaction.hide(showFragment);
        }

        Fragment mFragment = fragmentManager.findFragmentByTag(tag);
        if (mFragment != null) {
            fragmentTransaction.show(mFragment);
        } else {
            mFragment = fragment;
            fragmentTransaction.add(resid, mFragment, tag);
        }

        showFragment = mFragment;
        fragmentTransaction.commit();
    }
}
